﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace Fengsoft.AIBlog.Web.Code
{
    public abstract class ExtensionController:Controller
    {
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            string cultureName=CookieHelper.CultureName;
            if (string.IsNullOrEmpty(cultureName))
            {
                cultureName=requestContext.HttpContext.Request.UserLanguages[0]; // Obtain it from HTTP header AcceptLanguages.
            }
            // Validate culture name.
            cultureName=CultureHelper.GetValidCulture(cultureName); // This is safe.
            // Modify current thread's culture.
            Thread.CurrentThread.CurrentCulture=CultureInfo.CreateSpecificCulture(cultureName);
            Thread.CurrentThread.CurrentUICulture=CultureInfo.CreateSpecificCulture(cultureName);
            base.Initialize(requestContext);
        }
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Is it View?
            ViewResultBase view=filterContext.Result as ViewResultBase;
            if (view==null) // If not exit.
            {
                return;
            }
            string cultureName=Thread.CurrentThread.CurrentCulture.Name; // e.g. "en-US" // filterContext.HttpContext.Request.UserLanguages[0]; // needs validation return "en-us" as default.           
            // Is it default culture? exit
            if (cultureName==CultureHelper.GetDefaultCulture())
            {
                return;
            }
            // Are views implemented separately for this culture? if not exit.
            bool viewImplemented=CultureHelper.IsViewSeparate(cultureName);
            if (!viewImplemented)
            {
                return;
            }
            string viewName=view.ViewName;
            int i=0;
            if (string.IsNullOrEmpty(viewName))
            {
                viewName=string.Format("{0}.{1}",filterContext.RouteData.Values["action"],cultureName); // Index.en-US
            }
            else if ((i=viewName.IndexOf('.'))>0)
            {
                viewName=string.Format("{0}{1}{2}",viewName.Substring(0,i+1),cultureName,viewName.Substring(i)); // Contains . like "Index.cshtml"
            }
            else
            {
                viewName+=string.Format(".{0}",cultureName); // e.g. "Index" ==> "Index.en-Us".
            }
            view.ViewName=viewName;
            filterContext.Controller.ViewBag.CultureName=string.Format(".{0}",cultureName);
            base.OnActionExecuted(filterContext);
        }
    }
}